package dao

import (
	"errors"
	"github.com/douyu/jupiter/pkg/store/gorm"
	"jupiter-demo/internal/app/model/db"
	"time"
)

// User 指定Menu结构体对应的表名
type user struct {
	*gorm.DB
}

// InitUser ...
func InitUser(invokerDB *gorm.DB) *user {
	u := &user{
		DB: invokerDB,
	}
	return u
}


func (u *user) GetList(where db.User, currentPage, pageSize int, sort string) (out []db.User, total int, err error) {
	if pageSize == 0 {
		pageSize = 20
	}
	if currentPage == 0 {
		currentPage = 1
	}
	var resp []db.User
	sql := u.DB.Model(db.User{}).Where(where)
	sql.Count(&total)
	err = sql.Order(sort).Offset((currentPage - 1) * pageSize).Limit(pageSize).Find(&resp).Error
	if err != nil {
		return
	}
	for _, user := range resp {
		out = append(out, user)
	}
	return
}

//GetUserBuOaUID 根据oaUid获取用户
func (u *user) GetUserByName(name string) (userData db.User) {
	u.DB.Where("username=?", name).Find(&userData)
	return
}

//GetUserBuOaUID 根据oaUid获取用户
func (u *user) GetUserByUID(uid int) (userData db.User) {
	u.DB.Where("id=?", uid).Find(&userData)
	return
}

// GetNameByUID ...
func (u *user) GetNameByUID(uid int) string {
	var userData db.User
	u.DB.Where("id=?", uid).Find(&userData)
	return userData.UserName
}



func (u *user) Create(item *db.User) (err error) {
	err = u.DB.Where("user_name = ?", item.UserName).Find(item).Error
	if err != nil && !gorm.IsRecordNotFoundError(err) {
		return
	}
	if item.Id > 0 {
		err = errors.New("user name is exist")
		return
	}

	item.CreateTime = time.Now()
	item.UpdateTime = time.Now()
	err = u.DB.Create(item).Error
	return
}

func (u *user) Update(uid int, user *db.User) (err error) {
	var info db.User
	err = u.DB.Where("uid = ?", uid).Find(&info).Error
	if err != nil && !gorm.IsRecordNotFoundError(err) {
		return
	}
	if info.Id == 0 {
		err = errors.New("user is not exist")
		return
	}
	user.UpdateTime = time.Now()
	err = u.DB.Model(db.User{}).Where("uid = ?", uid).UpdateColumns(&user).Error
	return
}

func (u *user) Delete(item db.User) (err error) {
	var info db.User
	err = u.DB.Where("id = ?", item.Id).Find(&info).Error
	if err != nil && !gorm.IsRecordNotFoundError(err) {
		return
	}
	if info.Id == 0 {
		err = errors.New("用户不存在")
		return
	}
	err = u.DB.Where("id = ?", item.Id).Delete(&db.User{}).Error

	return
}








